<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Controller\user;

use App\Constants\Constants;
use App\Dao\CancellationDao;
use App\Dao\LocationDao;
use App\Kernel\Util\UserJwtInstance;
use App\Request\User\Auth\retrieveRequest;
use App\Request\User\User\ChangePasswordRequest;
use App\Request\User\User\UserPayPasswordRequest;
use App\Request\User\User\UpdatePayPasswordRequest;
use App\Request\User\User\CancellationRequest;
use App\Request\User\User\UserInfoRequest;
use App\Service\User\MoneyService;
use App\Service\User\UserService;
use App\Request\User\Auth\retrievePhoneRequest;
use App\Request\User\User\retrievePayPasswordRequest;
use App\Middleware\User\UserMiddleware;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;

/**
 * 用户控制器
 *
 * @AutoController()
 * @Middleware(UserMiddleware::class)
 * @author 刘兴永(aile8880@qq.com)
 * @package App\Controller\admin
 */
class UserController extends Controller
{
    /**
     * 用户服务
     *
     * @Inject
     * @var UserService
     */
    private $service;

    /**
     * @Inject
     * @var LocationDao
     */
    private $location_dao;

    /**
     * @Inject
     * @var MoneyService
     */
    public $money_service;

    /**
     * @Inject
     * @var CancellationDao
     */
    public $cancellation_dao;


    /**
     * 测试分佣配置文件
     */
    public function servantConfig()
    {
        var_dump(sConfig("store_coupon_part"));
    }

    /**
     * 线下扫码手动分佣
     */
    public function Manual()
    {
        $order_no = (string)$this->request->input('order_no', 0);

        $this->money_service->ScanBusinessBonus($order_no);

        $this->success();
    }

    /**
     * 用户分享参数
     */
    public function share()
    {
        $user = UserJwtInstance::instance()->build()->getUser();

        $result = [
            'identity_code' => $user->identity_code,
            'identity_code_url' => "https://share.sltvip.cn/?phone=".substr($user->phone,-4)."&invitation_code_id=".$user->identity_code
        ];
        $this->success($result);
    }

    /**
     * 用户资料接口
     */
    public function info()
    {
        $result = $this->service->getUserInfo();

        $this->success($result);
    }

    /**
     * 用户增加注册地址
     */
    public function userAdd()
    {

        $district_id = (int)$this->request->input('district_id', 0);

        $user = $this->service->dao->first(uid(),false);

        if( $user['province'] && $user['city'] &&  $user['district'] && $user['province_id'] && $user['city_id'] &&  $user['district_id']) {
            $this->error('USER.NOT_ADDR');
        }

        $district = $this->location_dao->getLocationByPid( [
            'pid' => $district_id
        ] );

        $city = $this->location_dao->getLocationByPid( [
            'pid' => $district['level']
        ] );

        $province = $this->location_dao->getLocationByPid( [
            'pid' => $city['level']
        ] );


        // 下级地区不属于上级地区返回错误
        if ($province->pid !== $city->level || $city->pid !== $district->level) {
            $this->error('BUSINESS.LOCATION_ERROR');
        }

        $update = $this->service->dao->update([
            'province' => $province['name'],
            'province_id' => $province['pid'],
            'city' => $city['name'],
            'city_id' => $city['pid'],
            'district' => $district['name'],
            'district_id' => $district['pid'],
        ]);

        !$update && $this->error();

        $this->success();
    }

    /**
     * 修改密码接口
     *
     * @param ChangePasswordRequest $request
     */
    public function change_password(ChangePasswordRequest $request)
    {
        $new_password = $request->input('old_password');
        $password = $request->input('password');

        $user = UserJwtInstance::instance()->build()->getUser();

        //验证密码
        if( !password_verify( $new_password, $user->login_pwd ) ) {
            $this->error('USER.OLD_PASSWORD_ERRORS');
        }

        $update = $this->service->dao->update([
            'login_pwd' => password_hash($password, PASSWORD_DEFAULT )
        ]);

        !$update && $this->error();

        $this->success();
    }

    /**
     * update
     *
     * @param UserInfoRequest $request
     */
    public function update(UserInfoRequest $request)
    {
        $params = $request->all();

        $field_all = array_intersect(array_keys($params), ['avatar','name', 'sex']);

        foreach ($field_all as $field) {
            $data[$field] = $params[$field];
        }

        $update = $this->service->dao->update($data);

        !$update && $this->error();

        $this->success();
    }

    /**
     * 判断用户是否有支付密码
     */
    public function is_safe_pwd()
    {
        $user = UserJwtInstance::instance()->build()->getUser();

        $result = 0;

        if( !empty($user->safe_pwd) ) {
            $result = 1;
        }

        $this->success($result);
    }

    /**
     *添加支付密码
     *
     * @param UserPayPasswordRequest $request
     */
    public function setPayPassword(UserPayPasswordRequest $request)
    {
        $params = $request->all();

        $update = $this->service->dao->update([
            'safe_pwd' => password_hash($params['password'], PASSWORD_DEFAULT )
        ]);

        !$update && $this->error();

        $this->success();
    }

    /**
     *修改支付密码
     *
     * @param UpdatePayPasswordRequest $request
     */
    public function updatePayPassword(UpdatePayPasswordRequest $request)
    {
        $new_password = $request->input('old_password');
        $password = $request->input('password');

        $user = UserJwtInstance::instance()->build()->getUser();

        //验证密码
        if( !password_verify( $new_password, $user->safe_pwd ) ) {
            $this->error('USER.OLD_PASSWORD_ERRORS');
        }

        $update = $this->service->dao->update([
            'safe_pwd' => password_hash($password, PASSWORD_DEFAULT )
        ]);

        !$update && $this->error();

        $this->success();
    }

    /**
     * 找回密码 - 验证手机
     *
     * @param retrievePhoneRequest $request
     */
    public function retrievePhone ( retrievePhoneRequest $request )
    {
        $params = $request->all();

        isset($params['phone']) && $params['phone'] = trim($params['phone']);
        isset($params['code']) && $params['code'] = trim($params['code']);

        $this->service->retrievePhone($params['phone'], $params['code']);

        $this->success();
    }

    /**
     * 找回密码
     *
     * @param retrievePayPasswordRequest $request
     */
    public function retrievePayPassword( retrievePayPasswordRequest $request )
    {
        $params = $request->all();

        isset($params['phone']) && $params['phone'] = trim($params['phone']);
        isset($params['login_pwd']) && $params['login_pwd'] = trim($params['login_pwd']);

        $update = $this->service->dao->update([
            'safe_pwd' => password_hash($params['login_pwd'], PASSWORD_DEFAULT )
        ]);

        !$update && $this->error();

        $this->success();
    }

    /**
     * 注销用户
     *
     * @param CancellationRequest $request
     */
    public function cancellation(CancellationRequest $request)
    {
        $params = $request->all();

        // 判断验证码是否输入正确
        $record = $this->redis->get(Constants::CODE_REDIS_PREFIX . $params['phone']);
        $record = !$record ?: json_decode($record, true);
        if (!$record || !isset($record['code']) || (string)$record['code'] !== $params['code']) {
            $this->error('COMMON.CODE_ERROR');
        }
        $this->redis->del(Constants::CODE_REDIS_PREFIX . $params['phone']);

        $this->cancellation_dao->create([
            'user_id' => uid(),
            'status' => 0,
            'reason' => $params['reason'],
            'created_at' => time(),
            'updated_at' => time(),
        ]);

        $result = $this->service->dao->update([
            'deleted_at' => time()
        ]);

        $result ? $this->success(): $this->error();
    }
}